<?php
class Agitum_Model_Tree extends Agitum_Model_Object 
{
	protected function init() 
	{
		parent::init();
			
		$this->_fields['pid'] = array_merge($this->_fields['pid'], array('label' => 'Родитель', 'readOnly' => false, 'DATA_TYPE' => 'reference'));
		$this->_fields['trail'] = array_merge($this->_fields['trail'], array('label' => 'Путь по дереву', 'readOnly' => true, 'DATA_TYPE' => 'hidden'));
		$this->_fields['level'] = array_merge($this->_fields['level'], array('label' => 'Уровень иерархии', 'readOnly' => true, 'DATA_TYPE' => 'hidden' ));
	}
	
	public function getParents () 
	{
		$select = Zend_Registry::get('Zend_Db')->select();
		$select->from($this->_name)
			->where( 'trail @>  ?', $this->trail)
			->order( 'trail' );
		$rows = $select->query()->fetchAll();	
		
		return $rows;
	}
	
	public function getChilds () 
	{
		$select = Zend_Registry::get('Zend_Db')->select();
		$select->from($this->_name)
			->where( new Zend_Db_Expr("trail ~ '". $this->trail . ".*{1}'") )
			->order( 'trail' );
		$rows = $select->query()->fetchAll();	
		
		return $rows;
	}
	
	public function getBranch() 
	{
		$select = Zend_Registry::get('Zend_Db')->select();
		$select->from($this->_name)
			->where( 'trail <@ ?', $this->trail)
			->order( 'trail' );
		$rows = $select->query()->fetchAll();	
		
		return $rows;
	}
	
	public function getTree() 
	{
		$select = Zend_Registry::get('Zend_Db')->select();
		$select->reset();
		$select->from($this->_name)
			->order( 'trail' );
		$rows = $select->query()->fetchAll();
		return $rows;
	}
	
	public function getTreeMap() 
	{
		$rows = $this->getTree();
    	$data = array();
    	foreach ( $rows as $i => $row) {
    		$data[$row['id']] = $row;
    	}
 		return $data;
	}
	
	public function save() {
		if ( $this->pid == '' ) {
			$this->pid = null;
		}
		parent::save();
	}
	
//	public function getBranch($asObjectArray = false) 
//	{
//		$select = $this->getDbTable()->select();
//		$select->from($this->_name)
//			->where( 'left_key > ?', $this->left_key)
//			->where( 'right_key < ?', $this->right_key)
//			->order( 'left_key' );
//		$rows = $select->query()->fetchAll();	
//		
//		return $asObjectArray ? 
//				$this->_buildObjectArray($rows) : $rows->toArray();
//	}
	
}